package connection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection {
	private static String driver = "com.mysql.jdbc.Driver";
	private static String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true";
	private static String userName = "root";// 获取用户名
	private static String password = "123456";// 获取密码
	private static Connection conn = null;

	static {
		try {
			Class.forName(driver);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}// 静态代码块加载驱动

	public static Connection getConnection() throws SQLException {
		if (conn == null) {
			conn = DriverManager.getConnection(url, userName, password);
			return conn;
		}
		return conn;
	}// 链接数据库

	public static void main(String[] args) {

		try {
			Connection conn = DBConnection.getConnection();
			if (conn != null) {
				System.out.println("数据库连接成功！");
			} else {
				System.out.println("数据库连接失败！");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}
}